<!--
 @description 选择商品
 @fileName AddProductDlg.vue
 @author zengqiongying
 @created 2024/08/19 09:15:30
-->
<template>
  <el-dialog
    ref="refDlg"
    v-el-drag-dialog
    width="700px"
    title="商品选择"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    class="dialog-content-no-padding-top"
    @close="closeDialog"
  >
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="选择" name="first">
        <table-box
          ref="refAllTable"
          :class="{'no-multiple':!multiple}"
          :table-config="tableConfig"
          :other-filters="otherFilters"
          :table-height="400"
          table-default-expand-all
          :table-row-key="tableRowKey"
          :table-row-class-name="tableRowClassName"
          :table-tree-props="{children: 'skus', hasChildren: 'hasChildren'}"
          :selected-arry.sync="tableSelected"
          :show-custom-setting="false"
          :show-custom-combine="false"
          :table-sortable="false"
          @row-dblclick="dbClickRow"
          @data-change="getProductTableData"
          @selection-change="handleSelectionChange"
        >
          <!--
          :show-selection="multiple"
          reserve-selection -->
          <el-table-column
            v-if="multiple"
            slot="before"
            type="selection"
            :selectable="tableSelectable"
            reserve-selection
            width="40"
          />
          <el-table-column
            v-else
            slot="before"
            type="index"
          />
        </table-box>
      </el-tab-pane>
      <el-tab-pane v-if="multiple" :label="`已选商品(${selectedProductData.length})`" name="second">
        <div class="table-list-box">
          <el-table
            style="width: 100%"
            :data="selectedProductData"
            :height="480"
            header-row-class-name="table-list-header"
            highlight-current-row
            border
          >
            <el-table-column type="index" label="序号" width="50" fixed="left" />
            <el-table-column prop="skuName" label="商品名称" min-width="200" />
            <el-table-column prop="skuCode" label="商品编码" width="150" />
            <el-table-column label="操作" width="80" fixed="right">
              <template v-slot="{row}">
                <el-button class="my-button" type="text" size="mini" @click="handleDeleteSelected(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">取 消</el-button>
      <el-button type="primary" size="mini" @click="handleSure">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'CombineAddProduct',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const that = this
    return {
      otherFilters: [
        // { id: 'state', property: 'state', operator: '=', value: 1 }
      ],
      paramsRaw: {},
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/gcenter/page`,
        onlySearchBar: true,
        tabIndex: 20,
        setting: [
          {
            prop: 'picUrl',
            label: '商品图片',
            width: 100,
            overflowHidden: false,
            sortable: false,
            type: 'hidden',
            align: 'center',
            render: (_h, row) => {
              const iconUrl = row.picUrl || ''
              if (iconUrl) {
                const url = that.formatImageUrl(iconUrl)
                return (<div class='cover-image'><img src={url} /></div>)
              }
              return ''
            }
          },
          {
            prop: 'name',
            label: '商品名称',
            minWidth: 200,
            formatData: ({ name, skuName }) => {
              return skuName || name
            }
          },
          {
            prop: 'code',
            label: '商品编码',
            minWidth: 150,
            formatData: ({ code, skuCode }) => {
              return skuCode || code
            }
          }
        ]
      },
      activeName: 'first',
      tableSelected: [], // 单选行
      selectedProductData: [], // 当前已选所有商品
      cancelSelectedProducts: [], // 临时存储非当前页的移除数据
      currentTableData: [], // 当前页表格数据
      allProductData: {} // 当前所查询的所有数据
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    allProductData: {
      handler(val, oldVal) {
        this.$nextTick(() => {
          this.reSetTableSelection()
        })
      },
      deep: true
    }
  },
  methods: {
    closeDialog() {
      /* this.selectedProductData.forEach(row => {
        this.$refs.refAllTable.toggleRowSelection(row, false)
      }) */

      this.$refs.refAllTable.clearSelection()
      this.selectedProductData = []
      this.tableSelected = []
      this.dialogShow = false
    },
    handleClick() {

    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      if (this.multiple) {
        const filterArr = this.selectedProductData.filter(item => item.skuCode === row.skuCode)
        return filterArr.length > 0 ? 'selected-highlight' : 'white-row'
      } else {
        return ''
      }
    },
    tableRowKey(row) {
      return row.rowId || `${row.keyIndex}_${row.id}`
    },
    // 复选框是否可选(组合商品可选，非组合商品可选)
    tableSelectable(row) {
      return !!row.skuCode
    },
    // 获取搜索产品表格数据变化
    getProductTableData(res) {
      if (res && res.data && res.data.records) {
        const { page } = res.data
        const skuList = []
        res.data.records.forEach(row => {
          const spuId = row.id
          if (row.skus && row.skus.length > 0) {
            row.skus.forEach(v => {
              this.$set(v, 'spuId', spuId)
              this.$set(v, 'rowId', `${spuId}_${v.id}`)
              skuList.push(v)
            })
          }
          this.$set(row, 'rowId', spuId)
        })
        this.currentTableData = skuList
        const selectKey = `${page}`
        if (this.allProductData[selectKey]) {
          this.allProductData[selectKey] = []
        }
        this.$set(this.allProductData, selectKey, skuList)
      }
    },
    // 刷新表格数据
    refreshTable(isInit) {
      this.$nextTick(() => {
        this.$refs.refAllTable.initTableData(isInit ? '' : 'onPage')
      })
    },
    // 重置当前页已选中产品的复选状态
    reSetTableSelection() {
      const cancelList = this.cancelSelectedProducts.filter(item => {
        const tmp = this.currentTableData.find(v => v.skuCode === item.skuCode)
        if (tmp && tmp.skuCode) { // 在当前页表格数据中则取消选中
          this.$refs.refAllTable.toggleRowSelection(item, false)
        }
        return tmp.length === 0 // 返回非当前页数据
      })
      this.cancelSelectedProducts = cancelList

      const initCheckedRows = []
      this.currentTableData.forEach(item => {
        const index = this.selectedProductData.findIndex(v => v.skuCode === item.skuCode)
        const tmp = this.selectedProductData[index] || null
        if (tmp && tmp.skuCode) {
          // 在当前页表格数据中数据选中
          this.selectedProductData.splice(index, 1)
          this.$refs.refAllTable.toggleRowSelection(tmp, false)
          initCheckedRows.push(item)
        }
      })
      initCheckedRows.forEach(item => {
        this.$refs.refAllTable.toggleRowSelection(item, true)
      })
    },
    // 产品复选框操作
    handleSelectionChange(rows) {
      const { selectedProductData = [] } = this
      // 过滤掉非当前页已删除的产品
      const enbleSelectRows = rows.filter(row => {
        const index = this.cancelSelectedProducts.findIndex(v => v.skuCode === row.skuCode)
        return index === -1
      })

      this.selectedProductData = enbleSelectRows.map(row => {
        // 检测当前复选行是否已选中
        const repeatPros = selectedProductData.filter(v => v.skuCode === row.skuCode)
        if (repeatPros && repeatPros.length) {
          return repeatPros[0] // 已选中
        } else {
          return row // 新添加
        }
      })
    },
    // 移除已选择产品
    handleDeleteSelected(row) {
      const tmp = this.currentTableData.filter(item => row.skuCode === item.skuCode)
      if (tmp.length > 0) { // 在当前页表格数据中则取消选中
        this.$refs.refAllTable.toggleRowSelection(tmp[0], false)
        const index = this.selectedProductData.findIndex(v => v.skuCode === tmp[0].skuCode)
        if (index > -1) {
          this.selectedProductData.splice(index, 1)
        }
      } else { // 未在当前表格数据中，则加入到取消选中的数据集中，并从已选产品表中删除
        let tmpArr = []
        for (const key in this.allProductData) {
          tmpArr = tmpArr.concat(this.allProductData[key])
        }
        const repeatRows = tmpArr.filter(item => row.skuCode === item.skuCode)
        if (repeatRows && repeatRows.length) {
          this.$refs.refAllTable.toggleRowSelection(repeatRows[0], false)
        }
        this.cancelSelectedProducts.push(row)
        const index = this.selectedProductData.findIndex(v => v.skuCode === row.skuCode)
        if (index > -1) {
          this.selectedProductData.splice(index, 1)
        }
      }
    },
    dbClickRow(row, e) {
      if (this.multiple) return
      if (row.skuCode) {
        this.tableSelected = [row]
        this.handleSure()
      }
    },
    handleSure() {
      if (!this.multiple) {
        if (this.tableSelected.length === 0 || !this.tableSelected[0].skuCode) {
          this.$message.warning('主商品只能选择SKU')
          return
        }
        this.$emit('change', this.tableSelected[0])
      } else {
        if (this.selectedProductData.length === 0) {
          this.$message.warning('请选择商品')
          return
        }
        const flag = this.selectedProductData.every(v => {
          return ![null, undefined, ''].includes(v.skuCode)
        })
        if (!flag) {
          this.$message.warning('只能选择SKU')
          return
        }
        const data = this.selectedProductData.map(v => {
          return {
            id: v.id,
            skuCode: v.skuCode,
            skuName: v.skuName,
            spuId: v.spuId
          }
        })
        this.$emit('change', data)
      }
      this.closeDialog()
    }
  }
}

</script>
<style lang='scss' scoped>
 .cover-image{
    padding: 5px 0;
    line-height: 0;
    font-size: 0;
    img{
      height: 40px;
      width: 40px;
      object-fit: contain;
    }
  }

  /deep/ .el-table [class*=el-table__row--level] .el-table__expand-icon{
    // float:left;
    // margin-top: 10px;
    position: absolute;
    left: -30px;
    top: 10px;
  }
  /deep/ .el-table__body td.el-table__cell{
    position: relative;
  }
  /deep/ .el-table th .el-checkbox{
    visibility: hidden;
  }
  /deep/ .white-row{
    background: #fff !important;
  }
  /deep/ .el-checkbox .is-disabled{
    visibility: hidden;
  }
  /deep/ .no-multiple{
    .el-table__cell:first-child  .cell{
      visibility: hidden;
    }
    .el-table [class*=el-table__row--level] .el-table__expand-icon{
      left: -40px;
    }
  }
</style>
